{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "# Pandas 字符串大小写转换\n",
        "\n",
        "本教程介绍Pandas中字符串大小写转换的方法，包括lower、upper、title、capitalize和swapcase。\n",
        "\n",
        "## 学习目标\n",
        "\n",
        "- 掌握str.lower()方法：转小写\n",
        "- 掌握str.upper()方法：转大写\n",
        "- 掌握str.title()方法：标题格式\n",
        "- 掌握str.capitalize()方法：首字母大写\n",
        "- 掌握str.swapcase()方法：大小写互换\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 1. 导入库\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 2,
      "metadata": {},
      "outputs": [],
      "source": [
        "import pandas as pd\n",
        "import numpy as np"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 2. 创建示例数据\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 3,
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "原始数据：\n",
            "          name          city                email\n",
            "0     JOHN DOE      New York     John@Example.COM\n",
            "1   jane smith   los angeles  jane.smith@test.org\n",
            "2   Bob Wilson       CHICAGO      BOB@COMPANY.NET\n",
            "3  ALICE BROWN       Houston       alice@demo.EDU\n",
            "4  michael Lee  PHILADELPHIA     Mike@Sample.INFO\n"
          ]
        }
      ],
      "source": [
        "# 创建示例数据\n",
        "data = {\n",
        "    'name': ['JOHN DOE', 'jane smith', 'Bob Wilson', 'ALICE BROWN', 'michael Lee'],\n",
        "    'city': ['New York', 'los angeles', 'CHICAGO', 'Houston', 'PHILADELPHIA'],\n",
        "    'email': ['John@Example.COM', 'jane.smith@test.org', 'BOB@COMPANY.NET', 'alice@demo.EDU', 'Mike@Sample.INFO']\n",
        "}\n",
        "\n",
        "df = pd.DataFrame(data)\n",
        "print(\"原始数据：\")\n",
        "print(df)\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 3. str.lower() - 转换为小写\n",
        "\n",
        "**功能**：将字符串中的所有字母转换为小写。\n",
        "\n",
        "**语法**：`Series.str.lower()`\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 4,
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "姓名转换为小写：\n",
            "          name   name_lower\n",
            "0     JOHN DOE     john doe\n",
            "1   jane smith   jane smith\n",
            "2   Bob Wilson   bob wilson\n",
            "3  ALICE BROWN  alice brown\n",
            "4  michael Lee  michael lee\n"
          ]
        }
      ],
      "source": [
        "# 将所有姓名转换为小写\n",
        "df['name_lower'] = df['name'].str.lower()\n",
        "\n",
        "print(\"姓名转换为小写：\")\n",
        "print(df[['name', 'name_lower']])\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 5,
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "邮箱转换为小写：\n",
            "                 email          email_lower\n",
            "0     John@Example.COM     john@example.com\n",
            "1  jane.smith@test.org  jane.smith@test.org\n",
            "2      BOB@COMPANY.NET      bob@company.net\n",
            "3       alice@demo.EDU       alice@demo.edu\n",
            "4     Mike@Sample.INFO     mike@sample.info\n"
          ]
        }
      ],
      "source": [
        "# 将邮箱转换为小写（常用于标准化邮箱地址）\n",
        "df['email_lower'] = df['email'].str.lower()\n",
        "\n",
        "print(\"邮箱转换为小写：\")\n",
        "print(df[['email', 'email_lower']])\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 4. str.upper() - 转换为大写\n",
        "\n",
        "**功能**：将字符串中的所有字母转换为大写。\n",
        "\n",
        "**语法**：`Series.str.upper()`\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 6,
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "城市名转换为大写：\n",
            "           city    city_upper\n",
            "0      New York      NEW YORK\n",
            "1   los angeles   LOS ANGELES\n",
            "2       CHICAGO       CHICAGO\n",
            "3       Houston       HOUSTON\n",
            "4  PHILADELPHIA  PHILADELPHIA\n"
          ]
        }
      ],
      "source": [
        "# 将所有城市名转换为大写\n",
        "df['city_upper'] = df['city'].str.upper()\n",
        "\n",
        "print(\"城市名转换为大写：\")\n",
        "print(df[['city', 'city_upper']])\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 7,
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "姓名转换为大写：\n",
            "          name   name_upper\n",
            "0     JOHN DOE     JOHN DOE\n",
            "1   jane smith   JANE SMITH\n",
            "2   Bob Wilson   BOB WILSON\n",
            "3  ALICE BROWN  ALICE BROWN\n",
            "4  michael Lee  MICHAEL LEE\n"
          ]
        }
      ],
      "source": [
        "# 将姓名转换为大写\n",
        "df['name_upper'] = df['name'].str.upper()\n",
        "\n",
        "print(\"姓名转换为大写：\")\n",
        "print(df[['name', 'name_upper']])\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 5. str.title() - 标题格式\n",
        "\n",
        "**功能**：将字符串转换为标题格式，每个单词的首字母大写，其余字母小写。\n",
        "\n",
        "**语法**：`Series.str.title()`\n",
        "\n",
        "**注意**：title()会将每个单词的首字母大写，无论原始大小写如何。\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 8,
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "姓名转换为标题格式：\n",
            "          name   name_title\n",
            "0     JOHN DOE     John Doe\n",
            "1   jane smith   Jane Smith\n",
            "2   Bob Wilson   Bob Wilson\n",
            "3  ALICE BROWN  Alice Brown\n",
            "4  michael Lee  Michael Lee\n"
          ]
        }
      ],
      "source": [
        "# 将姓名转换为标题格式\n",
        "df['name_title'] = df['name'].str.title()\n",
        "\n",
        "print(\"姓名转换为标题格式：\")\n",
        "print(df[['name', 'name_title']])\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 9,
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "城市名转换为标题格式：\n",
            "           city    city_title\n",
            "0      New York      New York\n",
            "1   los angeles   Los Angeles\n",
            "2       CHICAGO       Chicago\n",
            "3       Houston       Houston\n",
            "4  PHILADELPHIA  Philadelphia\n"
          ]
        }
      ],
      "source": [
        "# 将城市名转换为标题格式\n",
        "df['city_title'] = df['city'].str.title()\n",
        "\n",
        "print(\"城市名转换为标题格式：\")\n",
        "print(df[['city', 'city_title']])\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 6. str.capitalize() - 首字母大写\n",
        "\n",
        "**功能**：将字符串的第一个字母转换为大写，其余字母转换为小写。\n",
        "\n",
        "**语法**：`Series.str.capitalize()`\n",
        "\n",
        "**注意**：capitalize()只将整个字符串的第一个字符大写，与title()的区别是title()会将每个单词的首字母都大写。\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 10,
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "姓名转换为首字母大写：\n",
            "          name name_capitalize\n",
            "0     JOHN DOE        John doe\n",
            "1   jane smith      Jane smith\n",
            "2   Bob Wilson      Bob wilson\n",
            "3  ALICE BROWN     Alice brown\n",
            "4  michael Lee     Michael lee\n"
          ]
        }
      ],
      "source": [
        "# 将姓名转换为首字母大写格式\n",
        "df['name_capitalize'] = df['name'].str.capitalize()\n",
        "\n",
        "print(\"姓名转换为首字母大写：\")\n",
        "print(df[['name', 'name_capitalize']])\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 11,
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "title() vs capitalize() 对比：\n",
            "          name name_title_compare name_capitalize_compare\n",
            "0     JOHN DOE           John Doe                John doe\n",
            "1   jane smith         Jane Smith              Jane smith\n",
            "2   Bob Wilson         Bob Wilson              Bob wilson\n",
            "3  ALICE BROWN        Alice Brown             Alice brown\n",
            "4  michael Lee        Michael Lee             Michael lee\n"
          ]
        }
      ],
      "source": [
        "# 对比title()和capitalize()的区别\n",
        "df['name_title_compare'] = df['name'].str.title()\n",
        "df['name_capitalize_compare'] = df['name'].str.capitalize()\n",
        "\n",
        "print(\"title() vs capitalize() 对比：\")\n",
        "print(df[['name', 'name_title_compare', 'name_capitalize_compare']])\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "**区别说明**：\n",
        "- `title()`: 每个单词的首字母都大写，例如 \"John Doe\"\n",
        "- `capitalize()`: 只有第一个字符大写，其余都小写，例如 \"John doe\"\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 7. str.swapcase() - 大小写互换\n",
        "\n",
        "**功能**：将字符串中的大写字母转换为小写，小写字母转换为大写。\n",
        "\n",
        "**语法**：`Series.str.swapcase()`\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 12,
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "姓名大小写互换：\n",
            "          name name_swapcase\n",
            "0     JOHN DOE      john doe\n",
            "1   jane smith    JANE SMITH\n",
            "2   Bob Wilson    bOB wILSON\n",
            "3  ALICE BROWN   alice brown\n",
            "4  michael Lee   MICHAEL lEE\n"
          ]
        }
      ],
      "source": [
        "# 将姓名大小写互换\n",
        "df['name_swapcase'] = df['name'].str.swapcase()\n",
        "\n",
        "print(\"姓名大小写互换：\")\n",
        "print(df[['name', 'name_swapcase']])\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 13,
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "邮箱大小写互换：\n",
            "                 email       email_swapcase\n",
            "0     John@Example.COM     jOHN@eXAMPLE.com\n",
            "1  jane.smith@test.org  JANE.SMITH@TEST.ORG\n",
            "2      BOB@COMPANY.NET      bob@company.net\n",
            "3       alice@demo.EDU       ALICE@DEMO.edu\n",
            "4     Mike@Sample.INFO     mIKE@sAMPLE.info\n"
          ]
        }
      ],
      "source": [
        "# 将邮箱大小写互换\n",
        "df['email_swapcase'] = df['email'].str.swapcase()\n",
        "\n",
        "print(\"邮箱大小写互换：\")\n",
        "print(df[['email', 'email_swapcase']])\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 8. 综合示例：数据清洗和标准化\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 14,
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "原始数据：\n",
            "          product     category    brand\n",
            "0       iPhone 14  ELECTRONICS    Apple\n",
            "1  SAMSUNG GALAXY  electronics  Samsung\n",
            "2    google pixel  Electronics   Google\n",
            "3      OnePlus 10  ELECTRONICS  oneplus\n",
            "4       XIAOMI 13  electronics   XIAOMI\n",
            "\n",
            "==================================================\n",
            "\n",
            "标准化后的数据：\n",
            "          product product_standardized     category category_standardized  \\\n",
            "0       iPhone 14            Iphone 14  ELECTRONICS           Electronics   \n",
            "1  SAMSUNG GALAXY       Samsung Galaxy  electronics           Electronics   \n",
            "2    google pixel         Google Pixel  Electronics           Electronics   \n",
            "3      OnePlus 10           Oneplus 10  ELECTRONICS           Electronics   \n",
            "4       XIAOMI 13            Xiaomi 13  electronics           Electronics   \n",
            "\n",
            "     brand brand_standardized  \n",
            "0    Apple              Apple  \n",
            "1  Samsung            Samsung  \n",
            "2   Google             Google  \n",
            "3  oneplus            Oneplus  \n",
            "4   XIAOMI             Xiaomi  \n"
          ]
        }
      ],
      "source": [
        "# 创建新的示例数据\n",
        "df2 = pd.DataFrame({\n",
        "    'product': ['iPhone 14', 'SAMSUNG GALAXY', 'google pixel', 'OnePlus 10', 'XIAOMI 13'],\n",
        "    'category': ['ELECTRONICS', 'electronics', 'Electronics', 'ELECTRONICS', 'electronics'],\n",
        "    'brand': ['Apple', 'Samsung', 'Google', 'oneplus', 'XIAOMI']\n",
        "})\n",
        "\n",
        "print(\"原始数据：\")\n",
        "print(df2)\n",
        "print(\"\\n\" + \"=\"*50 + \"\\n\")\n",
        "\n",
        "# 数据标准化\n",
        "df2['product_standardized'] = df2['product'].str.title()  # 产品名标题格式\n",
        "df2['category_standardized'] = df2['category'].str.capitalize()  # 类别首字母大写\n",
        "df2['brand_standardized'] = df2['brand'].str.capitalize()  # 品牌首字母大写\n",
        "\n",
        "print(\"标准化后的数据：\")\n",
        "print(df2[['product', 'product_standardized', 'category', 'category_standardized', \n",
        "           'brand', 'brand_standardized']])\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 9. 处理缺失值\n",
        "\n",
        "**注意**：如果Series中包含NaN值，这些方法会保持NaN不变。\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 15,
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "包含缺失值的数据：\n",
            "         name\n",
            "0    JOHN DOE\n",
            "1        None\n",
            "2  jane smith\n",
            "3         NaN\n",
            "4  Bob Wilson\n",
            "\n",
            "==================================================\n",
            "\n",
            "处理后的数据（缺失值保持不变）：\n",
            "         name  name_lower  name_upper\n",
            "0    JOHN DOE    john doe    JOHN DOE\n",
            "1        None        None        None\n",
            "2  jane smith  jane smith  JANE SMITH\n",
            "3         NaN         NaN         NaN\n",
            "4  Bob Wilson  bob wilson  BOB WILSON\n"
          ]
        }
      ],
      "source": [
        "# 创建包含缺失值的数据\n",
        "df3 = pd.DataFrame({\n",
        "    'name': ['JOHN DOE', None, 'jane smith', np.nan, 'Bob Wilson']\n",
        "})\n",
        "\n",
        "print(\"包含缺失值的数据：\")\n",
        "print(df3)\n",
        "print(\"\\n\" + \"=\"*50 + \"\\n\")\n",
        "\n",
        "# 转换大小写，缺失值保持不变\n",
        "df3['name_lower'] = df3['name'].str.lower()\n",
        "df3['name_upper'] = df3['name'].str.upper()\n",
        "\n",
        "print(\"处理后的数据（缺失值保持不变）：\")\n",
        "print(df3)\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 10. 方法总结对比\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 16,
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "原始字符串: 'hello WORLD python'\n",
            "\n",
            "==================================================\n",
            "          方法                 结果\n",
            "     lower() hello world python\n",
            "     upper() HELLO WORLD PYTHON\n",
            "     title() Hello World Python\n",
            "capitalize() Hello world python\n",
            "  swapcase() HELLO world PYTHON\n"
          ]
        }
      ],
      "source": [
        "# 创建一个示例字符串来展示所有方法的效果\n",
        "example = pd.Series(['hello WORLD python'])\n",
        "\n",
        "result_comparison = pd.DataFrame({\n",
        "    '方法': ['lower()', 'upper()', 'title()', 'capitalize()', 'swapcase()'],\n",
        "    '结果': [\n",
        "        example.str.lower().iloc[0],\n",
        "        example.str.upper().iloc[0],\n",
        "        example.str.title().iloc[0],\n",
        "        example.str.capitalize().iloc[0],\n",
        "        example.str.swapcase().iloc[0]\n",
        "    ]\n",
        "})\n",
        "\n",
        "print(\"原始字符串: 'hello WORLD python'\")\n",
        "print(\"\\n\" + \"=\"*50)\n",
        "print(result_comparison.to_string(index=False))\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 11. 实际应用场景\n",
        "\n",
        "### 场景1：用户邮箱标准化\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 17,
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "原始邮箱:\n",
            "0    User@Example.COM\n",
            "1       USER@TEST.ORG\n",
            "2       user@demo.net\n",
            "dtype: object\n",
            "\n",
            "标准化后的邮箱:\n",
            "0    user@example.com\n",
            "1       user@test.org\n",
            "2       user@demo.net\n",
            "dtype: object\n"
          ]
        }
      ],
      "source": [
        "# 用户输入的邮箱可能大小写不一致，需要标准化为小写\n",
        "user_emails = pd.Series([\n",
        "    'User@Example.COM',\n",
        "    'USER@TEST.ORG',\n",
        "    'user@demo.net'\n",
        "])\n",
        "\n",
        "normalized_emails = user_emails.str.lower()\n",
        "print(\"原始邮箱:\")\n",
        "print(user_emails)\n",
        "print(\"\\n标准化后的邮箱:\")\n",
        "print(normalized_emails)\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### 场景2：姓名格式统一\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 18,
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "原始姓名:\n",
            "0       JOHN DOE\n",
            "1     jane smith\n",
            "2     bob wilson\n",
            "3    ALICE BROWN\n",
            "dtype: object\n",
            "\n",
            "格式化后的姓名:\n",
            "0       John Doe\n",
            "1     Jane Smith\n",
            "2     Bob Wilson\n",
            "3    Alice Brown\n",
            "dtype: object\n"
          ]
        }
      ],
      "source": [
        "# 统一姓名格式为标题格式\n",
        "names = pd.Series([\n",
        "    'JOHN DOE',\n",
        "    'jane smith',\n",
        "    'bob wilson',\n",
        "    'ALICE BROWN'\n",
        "])\n",
        "\n",
        "formatted_names = names.str.title()\n",
        "print(\"原始姓名:\")\n",
        "print(names)\n",
        "print(\"\\n格式化后的姓名:\")\n",
        "print(formatted_names)\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### 场景3：数据对比和去重\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 19,
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "原始数据:\n",
            "         name  value\n",
            "0    John Doe    100\n",
            "1    JOHN DOE    200\n",
            "2  jane smith    300\n",
            "3  Jane Smith    400\n",
            "\n",
            "重复检查（原始）:\n",
            "0    False\n",
            "1    False\n",
            "2    False\n",
            "3    False\n",
            "Name: name, dtype: bool\n",
            "\n",
            "重复检查（转换为小写后）:\n",
            "0    False\n",
            "1     True\n",
            "2    False\n",
            "3     True\n",
            "Name: name_lower, dtype: bool\n"
          ]
        }
      ],
      "source": [
        "# 由于大小写不一致，可能导致重复数据无法识别\n",
        "duplicate_data = pd.DataFrame({\n",
        "    'name': ['John Doe', 'JOHN DOE', 'jane smith', 'Jane Smith'],\n",
        "    'value': [100, 200, 300, 400]\n",
        "})\n",
        "\n",
        "print(\"原始数据:\")\n",
        "print(duplicate_data)\n",
        "print(\"\\n重复检查（原始）:\")\n",
        "print(duplicate_data['name'].duplicated())\n",
        "\n",
        "# 转换为小写后去重\n",
        "duplicate_data['name_lower'] = duplicate_data['name'].str.lower()\n",
        "print(\"\\n重复检查（转换为小写后）:\")\n",
        "print(duplicate_data['name_lower'].duplicated())\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 总结\n",
        "\n",
        "| 方法 | 功能 | 使用场景 |\n",
        "|------|------|----------|\n",
        "| `str.lower()` | 全部转小写 | 邮箱标准化、URL处理、大小写不敏感比较 |\n",
        "| `str.upper()` | 全部转大写 | 代码标识符、数据库字段名、显示强调 |\n",
        "| `str.title()` | 单词首字母大写 | 姓名格式化、标题格式化、文章标题 |\n",
        "| `str.capitalize()` | 首字母大写 | 句子开头、单个词格式化 |\n",
        "| `str.swapcase()` | 大小写互换 | 特殊格式转换、测试数据变换 |\n",
        "\n",
        "**重要提示**：\n",
        "1. 所有方法都返回新的Series，不修改原始数据\n",
        "2. NaN值会被保留，不会被转换\n",
        "3. 这些方法只对字符串类型的数据有效，确保Series的数据类型为object（字符串）\n"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "ml311",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.11.0"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 4
}
